<template>
  <div>
    <div ref="chart" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

const chart = ref<HTMLElement | null>(null);

onMounted(async () => {
  if (chart.value) {
    let myECharts = echarts.init(chart.value);

    try {
      // 使用 Axios 发送 HTTP GET 请求获取数据
      const response = await axios.get('http://127.0.0.1:5000/barr');
      const rawData = response.data;

      // 将 JSON 格式的字符串解析成 JavaScript 对象
      const parsedData = rawData.data;

      // 转换数据格式以适应 ECharts
      const data = parsedData.map(item => ({
        name: item.Origin,
        value: item.value
      }));

      // 配置项
      const option = {
        title: {
          text: '咖啡地区分布',
          
          textStyle: {
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        xAxis: {
          type: 'category',
          data: parsedData.map(item => item.Origin),
          axisLabel: {
            color: '#666',
            fontSize: 14
          },
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#666',
            fontSize: 14
          },
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          }
        },
        series: [{
          name: '咖啡类型',
          type: 'bar',
          data: parsedData.map(item => item.value),
          itemStyle: {
            color: '#2f4554' // 柱状图颜色
          }
        }]
      };

      // 使用配置项绘制图表
      myECharts.setOption(option);
    } catch (error) {
      console.error('Error fetching coffee data:', error);
    }
  }
});
</script>
